package org.wenbo.override.tools.ajax;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

public class List2Json {
	public static List2Json me(){
		return new List2Json();
	}
	@SuppressWarnings("rawtypes")
	public String getJsonData(List list, String callback)
			throws IllegalAccessException, NoSuchMethodException,
			InvocationTargetException {
		String jsonTemp = "var json=[";
		for (int i = 0; i < list.size(); i++) {
			jsonTemp = jsonTemp + "{";
			Field[] field = list.get(i).getClass().getDeclaredFields();// 获取参数数组
			for (int j = 0; j < field.length; j++) {
				Method metd = list
						.get(i)
						.getClass()
						.getMethod(
								"get"
										+ field[j].getName().substring(0, 1)
												.toUpperCase()
										+ field[j].getName().substring(1), null);// 根据字段名找到对应的get方法，null表示查找的方法无参数
				jsonTemp = jsonTemp + field[j].getName() + ":'"
						+ metd.invoke(list.get(i), null) + "'";// 调用找到的函数
				if (j != field.length - 1) {
					jsonTemp = jsonTemp + ",";
				}
			}
			if (i != list.size() - 1) {
				jsonTemp = jsonTemp + "},";
			} else {
				jsonTemp = jsonTemp + "}";
			}
		}
		jsonTemp = jsonTemp + "];(" + callback + ")()";
		return jsonTemp;
	}
}
